package com.tangcco.lockwell.controller.student;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONException;
import cn.hutool.json.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tangcco.lockwell.base.RestResponse;
import com.tangcco.lockwell.context.WebContext;
import com.tangcco.lockwell.domain.DataDictionary;
import com.tangcco.lockwell.domain.Message;
import com.tangcco.lockwell.domain.MessageLikesRecord;
import com.tangcco.lockwell.domain.User;
import com.tangcco.lockwell.domain.dto.message.MessageDto;
import com.tangcco.lockwell.service.DataDictionaryService;
import com.tangcco.lockwell.service.MessageLikesRecordService;
import com.tangcco.lockwell.service.MessageService;
import com.tangcco.lockwell.service.UserService;
import com.tangcco.lockwell.utility.AiUtil;
import com.tangcco.lockwell.utility.DateTimeUtil;
import com.tangcco.lockwell.utility.JsonUtil;
import com.tangcco.lockwell.utility.StudentSubjectUtil;
import com.tangcco.lockwell.viewmodel.admin.message.MessagePageRequestVM;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author yanxinping
 * @version 1.0
 * @description: TODO
 * @date 2024/12/23 10:37
 */
@Slf4j
@RestController
@RequestMapping("/api/student/message")
public class MessageInfoController {
    @Autowired
    private MessageService messageInfoService;
    @Autowired
    private StudentSubjectUtil studentSubjectUtil;
    @Autowired
    private WebContext webContext;
    @Autowired
    private UserService userService;
    @Autowired
    private DataDictionaryService dataDictionaryService;

    @Autowired
    private MessageLikesRecordService messageLikesRecordService;
    @Autowired
    private AiUtil aiUtil;
    @Autowired
    private MessageService messageService;

    @RequestMapping("/messgeList")
    public RestResponse<PageInfo<MessageDto>> getMessageList(@RequestParam(value = "page", defaultValue = "1") int page,
                                                              @RequestParam(value = "size", defaultValue = "10") int size) {
        PageHelper.startPage(page,size);
        PageHelper.orderBy("create_time desc");
        MessagePageRequestVM messagePageRequestVM = new MessagePageRequestVM();
        messagePageRequestVM.setPageIndex(page);
        messagePageRequestVM.setPageSize(size);
        PageInfo<Message> messageList = messageInfoService.selectPageForStudent(messagePageRequestVM);
        PageInfo<MessageDto> result = new PageInfo<>();
        BeanUtil.copyProperties(messageList, result);
        //因为是浅拷贝，所以list里面的对象还是原来的对象，所以需要重新赋值
        List<MessageDto> messageDtoList = new ArrayList<>();
        messageList.getList().forEach(message -> {
            MessageDto messageDto = new MessageDto();
            BeanUtil.copyProperties(message, messageDto);
            DataDictionary dataDictionary = dataDictionaryService.selectDataDictionaryById(Integer.parseInt(message.getSubjectId()));
            if(dataDictionary != null) {
                messageDto.setSubjectName(dataDictionary.getCategoryName());
            }
            messageDto.setUser(userService.getUserById(message.getUserId()));
            if(message.getCreateTime() != null){
                LocalDateTime localDateTime = LocalDateTimeUtil.parse(message.getCreateTime(), "yyyy-MM-dd HH:mm:ss");
                ZoneId zoneId = ZoneId.systemDefault();
                Date date = Date.from(localDateTime.atZone(zoneId).toInstant());
                messageDto.setTimeStr(DateTimeUtil.formatTimeSince(date.getTime()).isEmpty() ?message.getCreateTime():DateTimeUtil.formatTimeSince(date.getTime()));
            }
            messageDtoList.add(messageDto);
        });
        result.setList(messageDtoList);
        return RestResponse.ok(result);
    }

    /**
     * 发布消息或回复（用户学生端使用，老师和ai不走这个）
     * @return
     */
    @RequestMapping("/addMessage")
    public RestResponse addMessage(@RequestBody Map<String,Object> map) {
        Message message = new Message();
        if(map.get("subject") != null ){
            message.setSubjectId(String.valueOf(map.get("subject")));
        }
        if(map.get("content") != null ){
            message.setPublishContent(String.valueOf(map.get("content")));
        }
        if (map.get("file")!= null){
            message.setContentImageAddress(String.valueOf(map.get("file")));
        }
        if(map.get("belongs")!=null){
            message.setBelongs(String.valueOf(map.get("belongs")));
            message.setClassify(1);
        }
        User user = userService.getUserById(webContext.getCurrentUser().getUserId());
        if(user.getRole()!=null){
            if(user.getRole() == 3){
                message.setStatus(1);
            }else if(user.getRole() == 1){
                message.setStatus(0);
            }
        }
        message.setUserId(user.getUserId());
        message.setTime(DateTimeUtil.dateFormat(new Date()));
        messageInfoService.insertReply(message);
        //如果是初次发布，则调用ai答疑添加一条回复信息
        if(map.get("belongs") == null &&  map.get("content")!=null){
            messageService.insertByAiReply(message.getMessageId(), String.valueOf(map.get("content")),String.valueOf(map.get("subject")),webContext.getCurrentUser().getUserId());
        }
        return RestResponse.ok();
    }

    /**
     * 查询消息详情
     * @param id
     * @return
     */
    @RequestMapping("/getMessageInfo")
    public RestResponse<MessageDto> getMessageInfo(@RequestParam(value = "id") Integer id){
        Message message = messageInfoService.findById(id);
        MessageDto messageDto = BeanUtil.copyProperties(message, MessageDto.class);
        User user = userService.getUserById(message.getUserId());
        messageDto.setUser(user);

        LocalDateTime localDateTime = LocalDateTimeUtil.parse(message.getCreateTime(), "yyyy-MM-dd HH:mm:ss");
        ZoneId zoneId = ZoneId.systemDefault();
        Date date = Date.from(localDateTime.atZone(zoneId).toInstant());
        messageDto.setTimeStr(DateTimeUtil.formatTimeSince(date.getTime()).isEmpty() ?message.getCreateTime():DateTimeUtil.formatTimeSince(date.getTime()));

        return RestResponse.ok(messageDto);
    }

    /**
     * 查询回复列表
     * @param id
     * @return
     */
    @RequestMapping("/getReplyList")
    public RestResponse<List<MessageDto>> getReplyList(@RequestParam(value = "id") Integer id){
        List<Message> messageList =messageInfoService.findByPid(id);
        if(messageList == null || messageList.isEmpty()){
            return RestResponse.ok(new ArrayList<>());
        }
        List<MessageDto> messageDtoList = new ArrayList<>();
        messageList.forEach(message -> {
            MessageDto messageDto = new MessageDto();
            BeanUtil.copyProperties(message, messageDto);
            DataDictionary dataDictionary = dataDictionaryService.selectDataDictionaryById(Integer.parseInt(message.getSubjectId()));
            if(dataDictionary != null) {
                messageDto.setSubjectName(dataDictionary.getCategoryName());
            }
            messageDto.setUser(userService.getUserById(message.getUserId()));
            if(message.getCreateTime() != null){
                LocalDateTime localDateTime = LocalDateTimeUtil.parse(message.getCreateTime(), "yyyy-MM-dd HH:mm:ss");
                ZoneId zoneId = ZoneId.systemDefault();
                Date date = Date.from(localDateTime.atZone(zoneId).toInstant());
                messageDto.setTimeStr(DateTimeUtil.formatTimeSince(date.getTime()).isEmpty() ?message.getCreateTime():DateTimeUtil.formatTimeSince(date.getTime()));
            }
            //查询这条信息这个用户是否点赞了
            MessageLikesRecord mlr = new MessageLikesRecord();
            mlr.setMessageId(message.getMessageId());
            mlr.setLikesUserId(webContext.getCurrentUser().getUserId());
            List<MessageLikesRecord> likesRecordList = messageLikesRecordService.getLikesRecord(mlr);
            if(!CollectionUtils.isEmpty(likesRecordList)){
                messageDto.setLikesFlag(1);
            }else{
                messageDto.setLikesFlag(0);
            }
            String s = messageDto.getPublishContent().replace("\\n\\n", "<br>").replace("\\n", "<br>");
            messageDto.setPublishContent(s);
            List<Message> replyList = messageInfoService.findByPid(message.getMessageId());
            replyList = replyList.stream()
                    .sorted(Comparator.comparing(Message::getCreateTime).reversed())
                    .collect(Collectors.toList());
            List<MessageDto> replyDtoList = new ArrayList<>();
            if(replyList != null && !replyList.isEmpty()) {
                replyList.forEach(reply -> {
                    MessageDto replyDto = new MessageDto();
                    BeanUtil.copyProperties(reply, replyDto);
                    DataDictionary dataDictionary1 = dataDictionaryService.selectDataDictionaryById(Integer.parseInt(reply.getSubjectId()));
                    if(dataDictionary1 != null) {
                        replyDto.setSubjectName(dataDictionary1.getCategoryName());
                    }
                    replyDto.setUser(userService.getUserById(reply.getUserId()));
                    if(reply.getCreateTime() != null){
                        LocalDateTime localDateTime = LocalDateTimeUtil.parse(reply.getCreateTime(), "yyyy-MM-dd HH:mm:ss");
                        ZoneId zoneId = ZoneId.systemDefault();
                        Date date = Date.from(localDateTime.atZone(zoneId).toInstant());
                        replyDto.setTimeStr(DateTimeUtil.formatTimeSince(date.getTime()).isEmpty() ?reply.getCreateTime():DateTimeUtil.formatTimeSince(date.getTime()));
                    }
                    if(replyDto.getPublishContent()!=null){
                        replyDto.setPublishContent(replyDto.getPublishContent());
                    }
                    replyDtoList.add(replyDto);
                });
            }
            messageDto.setReplies(replyDtoList);
            messageDtoList.add(messageDto);
        });
        return RestResponse.ok(messageDtoList);
    }
}
